﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraCharts.Native;
using DevExpress.XtraTreeList.Nodes.Operations;
using EyFramework.Common;
using EyFramework.Library;
using EyFramework.ThirdPart.IdCard;
using Ncov2019.Core.Service;
using Ncov2019.Entity;

namespace Ncov2019
{
    public partial class FrmSingleOrder : FrmDevBase
    {
        private INcovOrderRecordService ncovOrderRecordService;
        private string Health;

        public FrmSingleOrder()
        {
            InitializeComponent();
            if(bool.Parse(Globals.GetSysConfig("AutoDetectIdCard", "true"))){
                timer1.Start();
            }
        }

        private void btnReadId_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            IdCardInfo idCard = IdCardService.ReadIDCard();
            tePatName.Text = idCard.Name;
            teIdNo.Text = idCard.CardNo;
            teAddress.Text = idCard.Address;
            if (idCard.Sex == "男")
            {
                cmbSex.SelectedIndex = 0;
            }
            else if (idCard.Sex == "女")
            {
                cmbSex.SelectedIndex = 1;
            }
            else
            {
                cmbSex.SelectedIndex = 2;
            }

            deBirthday.Text = TimeType(idCard.Birthday);
            var sInput = "shenfenzh= '" + teIdNo.Text + "'";
            var brxx = ncovOrderRecordService.SearchBrxx(sInput);
            if (brxx != null && brxx.Count > 0)
            {
                this.teTelphone.Text = brxx[0].JIATINGDH;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tePatName.Text = "";
            teIdNo.Text = "";
            teAddress.Text = "";
            teTelphone.Text = "";
            cmbSex.SelectedIndex = 3;
            deBirthday.Text = "";
            teBingrenid.Text = "";
            timer1.Start();
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            if (Globals.ShowYesNoAndTips("您正在进行免费核酸自助开单，是否继续?") == DialogResult.Yes)
            {
                SaveData();
            }
        }

        private void FrmSingleOrder_Load(object sender, EventArgs e)
        {
            ncovOrderRecordService = Globals.GetService<INcovOrderRecordService>();
        }

        private void SaveData()
        {
            if (!CheckData())
            {
                return;
            }

            NcovFreeOrderParam orderParam = new NcovFreeOrderParam()
            {
                PatName = tePatName.Text.Trim(),
                Sex = (cmbSex.SelectedIndex + 1).ToString(),
                Birthday = deBirthday.DateTime.ToString("yyyy-MM-dd"),
                IdNo = teIdNo.Text.Trim(),
                Address = teAddress.Text.Trim(),
                Telphone = teTelphone.Text.Trim(),
                Healthcode = Health
            };
            bool saveResult = false;
            //进行核酸自助机开单
            ShowLoading("请稍等");
            try
            {
                saveResult = ncovOrderRecordService.NcovFreeOrder(orderParam);
            }
            finally
            {
                CloseLoading();
            }
            if (saveResult)
            {
                this.DialogResult = DialogResult.OK;
                Globals.ShowTips("免费核酸自助开单成功");
                this.Close();
            }
            else
            {
                Globals.ShowError("免费核酸自助开单失败");
            }
        }

        private void QueryData()
        {
            throw new NotImplementedException();
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(tePatName.Text.Trim()))
            {
                Globals.ShowWarning("姓名不能为空！");
                tePatName.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(teIdNo.Text.Trim()))
            {
                Globals.ShowWarning("身份证号不能为空！");
                teIdNo.Focus();
                return false;
            }
            else
            {
                if (teIdNo.Text.Trim().Length != 15 && teIdNo.Text.Trim().Length != 18)
                {
                    Globals.ShowWarning("身份证号格式错误，15或18位！");
                    teIdNo.Focus();
                    return false;
                }
            }

            if (string.IsNullOrEmpty(teTelphone.Text.Trim()))
            {
                Globals.ShowWarning("联系电话不能为空！");
                teTelphone.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(teAddress.Text.Trim()))
            {
                Globals.ShowWarning("联系地址不能为空！");
                teAddress.Focus();
                return false;
            }

            if (greenCode.Checked)
            {
                Health = "1";
            }
            else if (yellowCode.Checked)
            {
                Health = "2";
            }
            else if (redCode.Checked)
            {
                Health = "3";
            }
            else if (orangeCode.Checked)
            {
                Health = "0";
            }
            else 
            {
                Globals.ShowWarning("请选择健康码！");
                return false;
            }
            return true;
        }

        private string TimeType(String time)
        {
            string str = time.Substring(0, 4) + "-" + time.Substring(4, 2) + "-" + time.Substring(6, 2);
            return str;
        }

        private void teIdNo_LocationChanged(object sender, EventArgs e)
        {
            deBirthday.Text = Globals.GetBirthByIdNo(teIdNo.Text);
            if (Globals.GetSexByIdNo(teIdNo.Text) == "男")
            {
                cmbSex.SelectedIndex = 0;
            }
            else if (Globals.GetSexByIdNo(teIdNo.Text) == "女")
            {
                cmbSex.SelectedIndex = 1;
            }
            else
            {
                cmbSex.SelectedIndex = 2;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            this.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {
                ReadIdCard();
            });
            task.Start();
        }

        private void ReadIdCard()
        {
            if (string.IsNullOrEmpty(tePatName.Text.Trim()))
            {
                Action act = delegate ()
                {
                    bool isExistIdCard = false;
                    try
                    {
                        isExistIdCard = IdCardService.ExistIDCard();
                    }
                    catch (Exception ex)
                    {
                        Globals.ShowError("检测身份证读卡器失败！");
                        timer1.Stop();
                        timer1.Enabled = false;
                        isExistIdCard = false;
                    }
                    if (IdCardService.ExistIDCard())
                    {
                        timer1.Stop();
                        IdCardInfo idCard = IdCardService.ReadIDCard();
                        tePatName.Text = idCard.Name;
                        teIdNo.Text = idCard.CardNo;
                        teAddress.Text = idCard.Address;
                        if (idCard.Sex == "男")
                        {
                            cmbSex.SelectedIndex = 0;
                        }
                        else if (idCard.Sex == "女")
                        {
                            cmbSex.SelectedIndex = 1;
                        }
                        else
                        {
                            cmbSex.SelectedIndex = 2;
                        }
                        deBirthday.Text = TimeType(idCard.Birthday);
                        var sInput = "shenfenzh= '" + teIdNo.Text + "'";
                        var brxx = ncovOrderRecordService.SearchBrxx(sInput);
                        if (brxx != null && brxx.Count > 0)
                        {
                            this.teTelphone.Text = brxx[0].JIATINGDH;
                        }
                    }
                };
                this.BeginInvoke(act);
            }
        }

        private void teBingrenid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13 && !string.IsNullOrEmpty(teBingrenid.Text.Trim()))
            {
                SearchBrxx(teBingrenid.Text.Trim());
            }
        }

        /// <summary>
        /// 根据病历号码获取病人信息
        /// </summary>
        /// <param name="sInput"></param>
        private void SearchBrxx(string sInput)
        {
            sInput = "bingrenid= '" + sInput + "'";
            var brxx = ncovOrderRecordService.SearchBrxx(sInput);
            if (brxx != null && brxx.Count > 0)
            {
                this.tePatName.Text = brxx[0].XINGMING;
                this.teIdNo.Text = brxx[0].SHENFENZH;
                this.teAddress.Text = brxx[0].JIATINGDZ;
                this.teTelphone.Text = brxx[0].JIATINGDH;
                this.deBirthday.Text = brxx[0].CHUSHENGRQ.Value.ToString("yyyy-MM-dd");
                if (brxx[0].XINGBIE == "男")
                {
                    cmbSex.SelectedIndex = 0;
                }
                else if (brxx[0].XINGBIE == "女")
                {
                    cmbSex.SelectedIndex = 1;
                }
                else
                {
                    cmbSex.SelectedIndex = 2;
                }
            }
        }

        private void teIdNo_KeyDown(object sender, KeyEventArgs e)
        {
            deBirthday.Text = Globals.GetBirthByIdNo(teIdNo.Text);
            if (Globals.GetSexByIdNo(teIdNo.Text) == "男")
            {
                cmbSex.SelectedIndex = 0;
            }
            else if (Globals.GetSexByIdNo(teIdNo.Text) == "女")
            {
                cmbSex.SelectedIndex = 1;
            }
            else
            {
                cmbSex.SelectedIndex = 2;
            }
            var sInput = "shenfenzh= '" + teIdNo.Text + "'";
            var brxx = ncovOrderRecordService.SearchBrxx(sInput);
            if (brxx != null && brxx.Count > 0)
            {
                this.teTelphone.Text = brxx[0].JIATINGDH;
                this.tePatName.Text = brxx[0].XINGMING;
                this.teAddress.Text = brxx[0].JIATINGDZ;
            }
        }
    }
}